package com.syj.jsxjj.ui.lend.activity;

import android.Manifest;
import android.content.Intent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.syj.jsxjj.R;
import com.syj.jsxjj.app.App;
import com.syj.jsxjj.base.BaseActivity;
import com.syj.jsxjj.base.PermissionsListener;
import com.syj.jsxjj.config.Constant;
import com.syj.jsxjj.dialog.AlertFragmentDialog;
import com.syj.jsxjj.events.LoanEvent;
import com.syj.jsxjj.events.PayLeanResultEvent;
import com.syj.jsxjj.events.RefreshUIEvent;
import com.syj.jsxjj.events.UIBaseEvent;
import com.syj.jsxjj.ui.lend.bean.ConfirmLoanBean;
import com.syj.jsxjj.ui.my.bean.UserInfoBean;
import com.syj.jsxjj.util.SpUtil;
import com.syj.jsxjj.util.Tool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;

import static com.syj.jsxjj.R.id.btn_next;
/**
 * 借款确认页面
 * Created by xiejingwen at 2017/2/15 0015
 */
public class LendConfirmLoanActivity extends BaseActivity {

    ConfirmLoanBean bean;
    @BindView(R.id.tv_loan_amount)
    TextView mTvLoanAmount;
    @BindView(R.id.tv_loan_period)
    TextView mTvLoanPeriod;
    @BindView(R.id.tv_real_amount)
    TextView mTvRealAmount;
    @BindView(R.id.tv_service_amount)
    TextView mTvServiceAmount;
    @BindView(R.id.content)
    LinearLayout mContent;
    @BindView(R.id.btn_next)
    TextView mBtnNext;
    @Override
    public int getLayoutId() {
        return R.layout.activity_lend_confirm_loan;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void loadData() {
        EventBus.getDefault().register(this);
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initView() {
        bean = getIntent().getParcelableExtra(BankInputPwdActivity.TAG_OPERATE_BEAN);
        mTitle.setTitle("借款");
        if (bean != null) {
            mTvLoanAmount.setText(bean.getMoney()+"（元）");
            mTvLoanPeriod.setText(bean.getPeriod()+"（天）");
            mTvRealAmount.setText(bean.getTrue_money()+"（元）");
            mTvServiceAmount.setText(bean.getCounter_fee()+"（元）");
        }
    }

    private void toLoan() {
        EventBus.getDefault().post(new LoanEvent(LendConfirmLoanActivity.this));
        App.loadingContent(mActivity,"正在申请中...");
        Tool.countTime(3, new Subscriber<Integer>() {
            @Override
            public void onCompleted() {
                App.hideLoading();
                new AlertFragmentDialog.Builder(mActivity).setContent("申请成功")
                        .setRightBtnText("确定")
                        .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                EventBus.getDefault().post(new RefreshUIEvent(UIBaseEvent.EVENT_LOAN_SUCCESS));
                                finish();
                            }
                        }).build();
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(Integer integer) {

            }
        });
        /*Intent intent = new Intent(LendConfirmLoanActivity.this, BankInputPwdActivity.class);
        intent.putExtra(BankInputPwdActivity.TAG_OPERATE, BankInputPwdActivity.TAG_OPERATE_LEND);
        intent.putExtra(BankInputPwdActivity.TAG_OPERATE_BEAN, bean);
        startActivity(intent);*/
    }

    /***********
     * eventBus 监听
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshUIEvent event) {
        //设置交易密码成功
        if (UIBaseEvent.EVENT_SET_PAYPWD == event.getType()) {
            bean.setReal_pay_pwd_status(SpUtil.getString(Constant.CACHE_PAY_PASS));
        } else if (UIBaseEvent.EVENT_LOAN_SUCCESS == event.getType()) {
            //SpUtil.putString(Constant.CACHE_LOAN_STATUS,Constant.CACHE_LOANED);//缓存借款状态为已借款
            //SpUtil.putLong(Constant.CACHE_TIME,System.currentTimeMillis());//缓存借款时间
            App.getConfig().getUserInfo().setLoanStatus(Constant.CACHE_LOANED);
            App.getConfig().getUserInfo().setLoanTime(System.currentTimeMillis());
            App.getConfig().setUserInfo(App.getConfig().getUserInfo());
            List<UserInfoBean> users = App.getConfig().getUsers();
            for (int i = 0; i < users.size(); i++) {
                if (users.get(i).getUsername().equals(App.getConfig().getUserInfo().getUsername())){
                    users.remove(i);
                    break;
                }
            }
            users.add(App.getConfig().getUserInfo());
            App.getConfig().setUsers(users);
            finish();
        } else if (UIBaseEvent.EVENT_LOAN_FAILED == event.getType()) {
            if (((PayLeanResultEvent) event).getErrMessage().equals("支付密码错误")) {
                new AlertFragmentDialog.Builder(mActivity)
                        .setContent(((PayLeanResultEvent) event).getErrMessage())
                        .setRightBtnText("重新输入")
                        .setRightCallBack(new AlertFragmentDialog.RightClickCallBack() {
                            @Override
                            public void dialogRightBtnClick() {
                                Intent intent = new Intent(LendConfirmLoanActivity.this, BankInputPwdActivity.class);
                                intent.putExtra(BankInputPwdActivity.TAG_OPERATE, BankInputPwdActivity.TAG_OPERATE_LEND);
                                intent.putExtra(BankInputPwdActivity.TAG_OPERATE_BEAN, getIntent().getParcelableExtra(BankInputPwdActivity.TAG_OPERATE_BEAN));
                                startActivity(intent);
                            }
                        }).setCancel(true).build();
                /*.setLeftBtnText("忘记密码")
                        .setLeftCallBack(new AlertFragmentDialog.LeftClickCallBack() {
                            @Override
                            public void dialogLeftBtnClick() {
                                Intent intent = new Intent(LendConfirmLoanActivity.this, ForgetPayPwdActivity.class);
                                startActivity(intent);
                            }

                        })*/
            } else {
                new AlertFragmentDialog.Builder(mActivity)
                        .setContent(((PayLeanResultEvent) event).getErrMessage())

                        .setRightBtnText("确定")
                        .build();
            }
        }
    }

    @OnClick({btn_next})
    public void onClick(View view) {
        if (Tool.isFastDoubleClick()) return;
        switch (view.getId()) {
            case btn_next:
                requestPermissions(new String[]{Manifest.permission.READ_SMS}, new PermissionsListener() {
                    @Override
                    public void onGranted() {
                        toLoan();
                    }

                    @Override
                    public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                        if (isNeverAsk) {
                            toAppSettings("缺少短信权限", false);
                        }
                    }
                });
                /*if (TextUtils.isEmpty(bean.getReal_pay_pwd_status())) {
                    Intent intent = new Intent(LendConfirmLoanActivity.this, SetTradePwdActivity.class);
                    startActivity(intent);
                } else {
                    requestPermissions(new String[]{Manifest.permission.READ_SMS}, new PermissionsListener() {
                        @Override
                        public void onGranted() {
                            toLoan();
                        }

                        @Override
                        public void onDenied(List<String> deniedPermissions, boolean isNeverAsk) {
                            if (isNeverAsk) {
                                toAppSettings("缺少短信权限", false);
                            }
                        }
                    });
                }*/
                break;
        }
    }
}
